package com.cxj.cxj_test_cloud.base.mvvm.model;

import com.cxj.cxj_test_cloud.common.callback.OnResponseCallback;
import com.cxj.cxj_test_cloud.common.rxjava.RxHttpCommonTransformer;
import com.cxj.cxj_test_cloud.common.rxjava.RxHttpResponseSubscriber;
import com.cxj.cxj_test_cloud.utils.Logger;

import javax.inject.Inject;

import io.reactivex.Flowable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

public class BaseModel {
    protected CompositeDisposable mCompositeDisposable;

    @Inject
    public BaseModel() {
        mCompositeDisposable = new CompositeDisposable();
    }


    public void request(Flowable flowable, boolean isShowLoading, OnResponseCallback responseCallback){
        mCompositeDisposable.add((Disposable) flowable.compose(new RxHttpCommonTransformer(isShowLoading, null))
                .subscribeWith(new RxHttpResponseSubscriber() {
                    @Override
                    public void onSuccess(Object response) {
                        if (response != null) {
                            responseCallback.onSuccess(response);
                        }
                    }

                    @Override
                    public void onError(int errorCode, String error) {
                        responseCallback.onFailure(errorCode, error);
                    }
                })
        );

    }

    /**
     * 释放资源
     */
    public void onCleared() {
        //取消订阅
        mCompositeDisposable.clear();
    }
}
